<template>
	<view class="vehicle-management">
		<!-- 搜索和筛选区域 -->
		<view class="search-filter">
			<view class="search-box">
				<image src="/static/icons/search.png" class="search-icon" mode="aspectFit" />
				<input type="text" placeholder="搜索车牌号或车型" class="search-input" v-model="searchText"
					@input="handleSearch" @focus="inputFocus" @blur="inputBlur" />
			</view>

			<view class="filter-options">
				<view class="filter-item" :class="{ active: filterStatus === 'all' }" @click="filterStatus = 'all'">
					全部
				</view>
				<view class="filter-item" :class="{ active: filterStatus === 'free' }" @click="filterStatus = 'free'">
					空闲
				</view>
				<view class="filter-item" :class="{ active: filterStatus === 'using' }" @click="filterStatus = 'using'">
					使用中
				</view>
				<view class="filter-item" :class="{ active: filterStatus === 'maintain' }"
					@click="filterStatus = 'maintain'">
					维修中
				</view>
			</view>
		</view>

		<!-- 车辆列表 - 使用scroll-view实现下拉刷新和上拉加载 -->
		<scroll-view class="vehicle-list" scroll-y ref="scrollView" @scrolltolower="loadMore"
			@refresherpulling="onPulling" @refresherrefresh="onRefresh" refresher-enabled refresher-threshold="80"
			refresher-default-style="black">
			<!-- 为列表项添加额外的容器，方便控制间距 -->
			<view class="vehicle-list-container">
				<view class="vehicle-card" v-for="(vehicle, index) in filteredVehicles" :key="vehicle.VehicleId">
					<!-- 车辆信息 -->
					<view class="vehicle-basic">
						<text class="vehicle-number">{{ vehicle.LicensePlate }}</text>
						<view class="vehicle-status" :class="getStatusClass(vehicle.Status)">
							{{ getStatusText(vehicle.Status) }}
						</view>
					</view>

					<view class="vehicle-details">
						<view class="detail-item">
							<text class="detail-label">车型:</text>
							<text class="detail-value">{{ vehicle.VehicleType }}</text>
						</view>
						<view class="detail-item">
							<text class="detail-label">核载:</text>
							<text class="detail-value">{{ vehicle.LoadCapacity }}人</text>
						</view>
					</view>

					<!-- 司机信息 -->
					<view class="driver-info" v-if="vehicle.DriverName">
						<text class="driver-label">司机信息</text>
						<text class="driver-value">{{ vehicle.DriverName }} - {{ vehicle.DriverPhone || '无电话' }}</text>
					</view>
					<view class="driver-info" v-else>
						<text class="driver-value">司机：未分配</text>
					</view>

					<!-- 操作按钮区域 -->
					<view class="vehicle-actions">
						<view class="action-btn edit-btn" @click.stop="goToDetail(vehicle.VehicleId)">
							<text class="action-text">编辑</text>
						</view>
						<view class="action-btn delete-btn" @click.stop="deleteCar(index, vehicle.VehicleId)">
							<text class="action-text">删除</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 加载状态 -->
			<view class="loading-status" v-if="loading">
				<view class="loading-spinner"></view>
				<text class="loading-text">加载中...</text>
			</view>

			<!-- 没有更多数据 -->
			<view class="no-more" v-if="!loading && hasMore === false && vehicles.length > 0">
				<text>没有更多数据了</text>
			</view>

			<!-- 空状态显示 -->
			<view class="empty-state" v-if="filteredVehicles.length === 0 && !loading">
				<image src="/static/icons/empty.png" class="empty-image" mode="aspectFit" />
				<text class="empty-text">暂无符合条件的车辆</text>
				<view class="empty-action" @click="resetFilter" v-if="searchText || filterStatus !== 'all'">
					<text>重置筛选条件</text>
				</view>
			</view>
		</scroll-view>

		<!-- 添加车辆的浮动按钮 -->
		<view class="add-button" @click="goToAddVehicle">
			<text>+</text>
		</view>
	</view>
</template>

<script>
	import {
		getVehicleList,
		deleteVehicleById
	} from '@/https/vehicle.js';

	export default {
		data() {
			return {
				// 搜索文本
				searchText: '',
				// 筛选状态
				filterStatus: 'all',
				// 车辆数据
				vehicles: [],
				// 加载状态
				loading: false,
				// 是否还有更多数据
				hasMore: true,
				// 当前页码
				currentPage: 1,
				// 每页数量
				pageSize: 5,
				// 总页数
				totalPages: 1,
				// 防抖时间戳
				lastLoadTime: 0
			};
		},

		computed: {
			// 根据搜索和筛选条件过滤车辆
			filteredVehicles() {
				return this.vehicles.filter(vehicle => {
					// 状态筛选
					let statusMatch = true;
					if (this.filterStatus !== 'all') {
						const statusMap = {
							'free': 0,
							'using': 1,
							'maintain': 2
						};
						statusMatch = vehicle.Status === statusMap[this.filterStatus];
					}

					// 搜索筛选
					const searchMatch = this.searchText === '' ||
						vehicle.LicensePlate.includes(this.searchText) ||
						vehicle.VehicleType.includes(this.searchText) ||
						(vehicle.DriverName && vehicle.DriverName.includes(this.searchText));

					return statusMatch && searchMatch;
				});
			}
		},

		onShow() {
			// 刷新数据
			this.loadVehicles(true);
		},

		onLoad() {
			// 初始加载数据
			this.loadVehicles(true);
		},

		methods: {
			// 加载车辆数据
			async loadVehicles(isRefresh = false) {
				// 如果是刷新，重置页码
				if (isRefresh) {
					this.currentPage = 1;
					this.vehicles = [];
					this.hasMore = true; // 重置是否有更多数据
				}

				// 如果没有更多数据或正在加载，直接返回
				if (this.loading || !this.hasMore) return;

				this.loading = true;

				try {
					// 构建请求参数
					const params = {
						OpenId: null, // 可以根据需求设置
						LicensePlate: this.searchText || null,
						VehicleType: null,
						Status: this.filterStatus !== 'all' ? {
							'free': 0,
							'using': 1,
							'maintain': 2
						} [this.filterStatus] : null,
						PageNum: this.currentPage,
						PageSize: this.pageSize,
						TotalNum: 0
					};

					// 调用API获取车辆列表
					const res = await getVehicleList(params);

					// 处理返回的数据
					if (res && Array.isArray(res.result)) {
						// 转换数据格式，确保与页面展示需求匹配
						const formattedData = res.result.map(vehicle => ({
							VehicleId: vehicle.vehicleId,
							LicensePlate: vehicle.licensePlate,
							VehicleType: vehicle.vehicleType,
							LoadCapacity: vehicle.loadCapacity,
							Status: vehicle.status,
							DriverName: vehicle.driverName || '',
							DriverPhone: vehicle.driverPhone || ''
						}));

						// 更新列表数据
						if (isRefresh) {
							this.vehicles = formattedData;
						} else {
							this.vehicles.push(...formattedData);
						}

						// 判断是否还有更多数据
						this.hasMore = formattedData.length === this.pageSize;

						// 如果是刷新且数据为空，显示空状态提示
						if (isRefresh && formattedData.length === 0) {
							uni.showToast({
								title: '暂无车辆数据',
								icon: 'none'
							});
						}
					} else {
						// 如果返回的数据格式不符合预期
						if (isRefresh) {
							this.vehicles = [];
							uni.showToast({
								title: '暂无车辆数据',
								icon: 'none'
							});
						}
						this.hasMore = false;
					}

					// 页码加1
					this.currentPage++;
				} catch (error) {
					console.error('加载车辆列表失败:', error);
					uni.showToast({
						title: error.message || '获取车辆列表失败，请检查网络连接',
						icon: 'none',
						duration: 2000
					});
					// 出错时清空列表（仅在刷新模式下）
					if (isRefresh) {
						this.vehicles = [];
					}
					this.hasMore = false;
				} finally {
					this.loading = false;
				}
			},

			// 处理搜索输入
			handleSearch() {
				// 搜索时重置页码
				this.currentPage = 1;
			},

			// 下拉刷新
			async onRefresh() {
				try {
					await this.loadVehicles(true);
				} finally {
					// 确保刷新动画停止
					setTimeout(() => {
						uni.stopPullDownRefresh();
					}, 300);
				}
			},

			// 下拉刷新过程中
			onPulling() {
				// 可以在这里添加一些下拉过程中的动画效果
			},

			// 上拉加载更多 - 添加防抖
			loadMore() {
				const now = Date.now();
				if (!this.loading && this.hasMore && now - this.lastLoadTime > 500) {
					this.lastLoadTime = now;
					this.loadVehicles();
				}
			},

			// 重置筛选条件
			resetFilter() {
				this.searchText = '';
				this.filterStatus = 'all';
				this.currentPage = 1;
				this.loadVehicles(true);
			},

			// 输入框聚焦
			inputFocus() {
				// 可以添加输入框聚焦时的效果
			},

			// 输入框失焦
			inputBlur() {
				// 可以添加输入框失焦时的效果
			},

			// 获取车辆状态文本
			getStatusText(status) {
				switch (status) {
					case 0:
						return '可用';
					case 1:
						return '维修中';
					case 2:
						return '已停用';
					default:
						return '未知';
				}
			},

			// 获取状态样式类名
			getStatusClass(status) {
				switch (status) {
					case 0:
						return 'status-free';
					case 1:
						return 'status-maintain';
					case 2:
						return 'status-disabled';
					default:
						return '';
				}
			},

			// 跳转到车辆编辑页
			goToDetail(id) {
				// 确保ID有效
				if (!id) {
					uni.showToast({
						title: '车辆ID无效',
						icon: 'none'
					});
					return;
				}

				try {
					uni.navigateTo({
						url: `/pages/cars/car-allocate?id=${id}`,
						fail: () => {
							uni.showToast({
								title: '导航失败，请重试',
								icon: 'none'
							});
						}
					});
				} catch (error) {
					// 静默捕获异常
				}
			},

			// 跳转到添加车辆页面
			goToAddVehicle() {
				uni.navigateTo({
					url: `/pages/cars/car-allocate?mode=add`
				});
			},

			// 删除车辆
			async deleteCar(index, carId) {
				// 确保ID有效
				if (!carId) {
					uni.showToast({
						title: '车辆ID无效',
						icon: 'none'
					});
					return;
				}

				uni.showModal({
					title: '确认删除',
					content: '确定要删除该车辆吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								// 显示加载提示
								uni.showLoading({
									title: '删除中...'
								});

								// 调用API删除车辆
								await deleteVehicleById(parseInt(carId));

								// 移除本地列表项
								this.vehicles.splice(index, 1);

								uni.showToast({
									title: '删除成功',
									icon: 'success'
								});

								// 刷新列表获取最新数据
								await this.loadVehicles(true);
							} catch (error) {
								console.error('删除车辆失败:', error);
								uni.showToast({
									title: '删除失败: ' + (error.message || ''),
									icon: 'none'
								});
							} finally {
								// 确保加载提示被隐藏
								uni.hideLoading();
							}
						}
					},
					// 添加fail回调处理模态框显示失败的情况
					fail: () => {
						// 静默处理失败情况
					}
				});
			}
		}
	};
</script>

<style scoped>
	.vehicle-management {
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	/* 搜索和筛选区域样式 */
	.search-filter {
		padding: 20rpx 30rpx;
		background-color: #fff;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		position: sticky;
		top: 0;
		z-index: 10;
	}

	.search-box {
		display: flex;
		align-items: center;
		background-color: #f5f5f5;
		border-radius: 60rpx;
		padding: 15rpx 25rpx;
		margin-bottom: 20rpx;
		transition: all 0.3s ease;
	}

	.search-box:focus-within {
		box-shadow: 0 0 0 2rpx #007aff;
		background-color: #fff;
	}

	.search-icon {
		width: 30rpx;
		height: 30rpx;
		margin-right: 15rpx;
		opacity: 0.5;
	}

	.search-input {
		flex: 1;
		font-size: 28rpx;
		color: #333;
		background-color: transparent;
		height: 40rpx;
		line-height: 40rpx;
	}

	.search-input::placeholder {
		color: #ccc;
	}

	.filter-options {
		display: flex;
		justify-content: space-between;
		overflow-x: auto;
		padding-bottom: 5rpx;
		scrollbar-width: none;
	}

	.filter-options::-webkit-scrollbar {
		display: none;
	}

	.filter-item {
		padding: 10rpx 20rpx;
		font-size: 28rpx;
		color: #666;
		position: relative;
		margin-right: 10rpx;
		white-space: nowrap;
		border-radius: 40rpx;
		transition: all 0.2s ease;
	}

	.filter-item:last-child {
		margin-right: 0;
	}

	.filter-item:active {
		background-color: #f0f0f0;
	}

	.filter-item.active {
		color: #007aff;
		font-weight: bold;
	}

	.filter-item.active::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		width: 60%;
		height: 4rpx;
		background-color: #007aff;
		border-radius: 2rpx;
	}

	/* 车辆列表样式 */
	.vehicle-list {
		padding: 20rpx 0;
		height: calc(100vh - 220rpx);
	}

	/* 新增容器用于控制卡片间距 */
	.vehicle-list-container {
		padding: 0 40rpx;
		box-sizing: border-box;
	}

	.vehicle-card {
		background-color: #fff;
		border-radius: 16rpx;
		overflow: hidden;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		transition: all 0.3s ease;
		padding: 30rpx;
		/* 确保内容不过度挤压 */
		min-height: 200rpx;
		box-sizing: border-box;
	}

	.vehicle-card:active {
		transform: scale(0.99);
		background-color: #f9f9f9;
	}

	.vehicle-basic {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.vehicle-number {
		font-size: 34rpx;
		font-weight: bold;
		color: #333;
	}

	.vehicle-status {
		padding: 5rpx 15rpx;
		border-radius: 20rpx;
		font-size: 24rpx;
	}

	.status-free {
		background-color: #e6f7ff;
		color: #1890ff;
	}

	.status-maintain {
		background-color: #fff2f0;
		color: #f5222d;
	}

	.status-disabled {
		background-color: #f5f5f5;
		color: #999;
	}

	.vehicle-details {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
		margin-top: 15rpx;
	}

	.detail-item {
		display: flex;
		align-items: center;
		margin-right: 20rpx;
		margin-bottom: 10rpx;
	}

	.detail-label {
		font-size: 24rpx;
		color: #666;
		margin-right: 8rpx;
	}

	.detail-value {
		font-size: 24rpx;
		color: #333;
		font-weight: 500;
	}

	.driver-info {
		margin-top: 15rpx;
		padding-top: 15rpx;
		border-top: 1rpx solid #f0f0f0;
	}

	.driver-label {
		font-size: 24rpx;
		color: #666;
		margin-bottom: 5rpx;
	}

	.driver-value {
		font-size: 24rpx;
		color: #333;
	}

	/* 车辆操作按钮样式 */
	.vehicle-actions {
		display: flex;
		justify-content: flex-end;
		border-top: 1rpx solid #eee;
		padding-top: 20rpx;
		margin-top: 15rpx;
	}

	.action-btn {
		padding: 10rpx 30rpx;
		border-radius: 12rpx;
		margin-left: 20rpx;
	}

	/* 按钮点击效果优化 */
	.action-btn:active {
		opacity: 0.8;
		transform: scale(0.98);
	}

	.edit-btn {
		background-color: #e6f2ff;
		color: #007aff;
	}

	.delete-btn {
		background-color: #ffe6e6;
		color: #ff6666;
	}

	.action-text {
		font-size: 28rpx;
	}

	/* 加载状态样式 */
	.loading-status {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 40rpx 0;
	}

	.loading-spinner {
		width: 40rpx;
		height: 40rpx;
		border: 4rpx solid #eee;
		border-top-color: #007aff;
		border-radius: 50%;
		animation: spin 1s linear infinite;
		margin-bottom: 15rpx;
	}

	.loading-text {
		font-size: 26rpx;
		color: #999;
	}

	/* 没有更多数据 */
	.no-more {
		text-align: center;
		padding: 30rpx 0;
		color: #999;
		font-size: 26rpx;
	}

	/* 空状态样式 */
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 100rpx 0;
		text-align: center;
	}

	.empty-image {
		width: 180rpx;
		height: 180rpx;
		margin-bottom: 30rpx;
		opacity: 0.5;
	}

	.empty-text {
		font-size: 30rpx;
		color: #999;
		margin-bottom: 30rpx;
	}

	.empty-action {
		padding: 12rpx 30rpx;
		background-color: #007aff;
		color: white;
		border-radius: 40rpx;
		font-size: 26rpx;
		transition: all 0.2s;
	}

	.empty-action:active {
		background-color: #0066cc;
		transform: scale(0.95);
	}

	/* 添加车辆的浮动按钮样式 */
	.add-button {
		position: fixed;
		right: 40rpx;
		bottom: 40rpx;
		width: 90rpx;
		height: 90rpx;
		background-color: #007aff;
		color: white;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 50rpx;
		font-weight: bold;
		box-shadow: 0 4rpx 15rpx rgba(0, 122, 255, 0.4);
		z-index: 99;
		transition: all 0.2s ease;
	}

	.add-button:active {
		transform: scale(0.95);
		background-color: #0066cc;
	}

	/* 动画定义 */
	@keyframes spin {
		to {
			transform: rotate(360deg);
		}
	}
</style>